package com.lishem.nettymain.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class Client {

    /***
     * 启动客户端
     * @param host:要访问要链接的服务端IP
     * @param port:要访问要链接的服务端Port
     */
    public void start(String host, int port) {
        //4:向远程服务发送数据->线程
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            //1:创建启动客户端对象
            Bootstrap bootstrap = new Bootstrap();
            ChannelFuture future = bootstrap.group(worker)
                    //TCP请求对应的Channel
                    .channel(NioSocketChannel.class)
                    // TODO 业务处理
                    .handler(new MyClientChannelHandler())
                    //2:为启动对象配置要访问的服务IP、Port,建立远程连接
                    .connect(host, port).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }

    /****
     * Netty客户端
     */
    public static void main(String[] args) {
        Client myClientServer = new Client();
        myClientServer.start("127.0.0.1",5566);
    }
}
